/*
 *  Copyright (c) 2018. 玺得（深圳）科技有限公司.保留所有权利. http://www.pi-top.com/ 玺得（深圳）科技有限公司保留所有代码著作权.如有任何疑问请访问官方网站与我们联系. 代码只针对特定需求定制编码，不得在未经允许或授权的情况下对外传播扩散.恶意传播者，法律后果自行承担. 本代码仅用于pps-cloud系统.
 */
package com.pitop.order.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baidu.fsg.uid.UidGenerator;
import com.pitop.core.base.BaseDAO;
import com.pitop.core.base.BaseSVImpl;
import com.pitop.core.entity.Page;
import com.pitop.core.exceptions.BaseException;
import com.pitop.core.exceptions.OrderException;
import com.pitop.order.dao.OrderDAO;
import com.pitop.order.dao.OrderDetailDAO;
import com.pitop.order.dao.OrderTraceDAO;
import com.pitop.order.entity.*;
import com.pitop.sync.entity.SyncTraceModel;
import com.pitop.sync.entity.SyncTraceState;
import com.pitop.sync.service.SyncDataTraceSV;
import com.pitop.sync.service.SyncTraceSV;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.HashedMap;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("orderSV")
@Slf4j
public class OrderSVImpl extends BaseSVImpl<Order, Long> implements OrderSV {

    @Autowired
    private OrderDAO orderDAO;

    @Autowired
    private OrderDetailDAO orderDetailDAO;

    @Autowired
    private OrderTraceDAO orderTraceDAO;

    @Autowired
    private SyncTraceSV syncTraceSV;

    @Autowired
    private SyncDataTraceSV syncDataTraceSV;

    @Resource
    private UidGenerator uidGenerator;

    @Override
    protected BaseDAO getBaseDAO() {
        return orderDAO;
    }

    /**
     * 保存account对象
     *
     * @param entity 实体
     * @throws BaseException
     */
    @Override
    public void save(Order entity) throws BaseException {
        entity.setCode(String.valueOf(uidGenerator.getUID()));
        entity.setCreateTime(new Date());
        entity.setUpdateTime(new Date());
        super.save(entity);
    }

    /**
     * 加载一个对象Order
     *
     * @param id * @param code 编码
     * @return Order
     */
    @Override
    public Order load(Long id, String code) {
        if (id == null && code == null) {
            throw new OrderException(BaseException.BaseExceptionEnum.Illegal_Param);
        }

        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("code", code);
        return orderDAO.load(param);
    }

    /**
     * 加载一个对象Order 通过id
     *
     * @param id
     * @return Order
     */
    @Override
    public Order loadById(Long id) {
        if (id == null) {
            throw new OrderException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        return orderDAO.loadById(id);
    }

    /**
     * 加载一个对象Order 通过code
     *
     * @param code 编码
     * @return Order
     */
    @Override
    public Order loadByCode(String code) {
        if (code == null) {
            throw new OrderException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        return orderDAO.loadByCode(code);
    }


    /**
     * 根据主键id,oldStates 共同更新 Order 的状态到newState状态
     *
     * @param id
     * @param newState  新状态
     * @param oldStates 旧状态集合
     */
    @Override
    public void updateStateById(Long id, OrderState newState, OrderState... oldStates) {
        if (id == null) {
            throw new OrderException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        if (newState == null) {
            throw new OrderException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        if (oldStates == null) {
            throw new OrderException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        String[] states = new String[oldStates.length];
        for (int i = 0; i < oldStates.length; i++) {
            states[i] = oldStates[i].name();
        }
        orderDAO.updateStateById(id, new Date(), newState.name(), states);
    }

    /**
     * 根据主键code,oldStates 共同更新 Order 的状态到newState状态
     *
     * @param code      编码
     * @param newState  新状态
     * @param oldStates 旧状态集合
     */
    @Override
    public void updateStateByCode(String code, OrderState newState, OrderState... oldStates) {
        if (code == null) {
            throw new OrderException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        if (newState == null) {
            throw new OrderException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        if (oldStates == null) {
            throw new OrderException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        String[] states = new String[oldStates.length];
        for (int i = 0; i < oldStates.length; i++) {
            states[i] = oldStates[i].name();
        }
        orderDAO.updateStateByCode(code, new Date(), newState.name(), states);
    }

    /**
     * 根据主键id 更新 Order 的状态到另一个状态
     *
     * @param id
     * @param state 状态
     */
    @Override
    public void updateById(Long id, OrderState state) {
        if (id == null) {
            throw new OrderException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        orderDAO.updateById(id, state.name(), new Date());
    }

    /**
     * 根据主键code 更新 Order 的状态到另一个状态
     *
     * @param code  编码
     * @param state 状态
     */
    @Override
    public void updateByCode(String code, OrderState state) {
        if (code == null) {
            throw new OrderException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        orderDAO.updateByCode(code, state.name(), new Date());
    }


    /**
     * 删除对象Order
     *
     * @param id * @param code 编码
     * @return Order
     */
    @Override
    public void delete(Long id, String code) {
        if (id == null && code == null) {
            throw new OrderException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("code", code);
        orderDAO.delete(param);
    }


    /**
     * 查询Order分页
     *
     * @param order  对象
     * @param offset 查询开始行
     * @param limit  查询行数
     * @return List<Order>
     */
    @Override
    public List<Order> list(Order order, int offset, int limit) {
        if (offset < 0) {
            offset = 0;
        }

        if (limit < 0) {
            limit = Page.limit;
        }

        Map<String, Object> map = null;
        if (order != null) {
            map = JSON.parseObject(JSON.toJSONString(order, SerializerFeature.WriteDateUseDateFormat));
        } else {
            map = new HashMap<>();
        }
        return orderDAO.list(map, new RowBounds(offset, limit));
    }

    @Override
    public int count(Order order) {
        Map<String, Object> map = null;
        if (order != null) {
            map = JSON.parseObject(JSON.toJSONString(order, SerializerFeature.WriteDateUseDateFormat));
        } else {
            map = new HashMap<>();
        }
        return orderDAO.count(map);
    }

    /**
     * 查询Order分页
     *
     * @param id     * @param code  编码
     * @param offset 查询开始行
     * @param limit  查询行数
     * @return List<Order>
     */
    @Override
    public List<Order> list(Long id, String code, int offset, int limit) {
        if (offset < 0) {
            offset = 0;
        }

        if (limit < 0) {
            limit = Page.limit;
        }
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("code", code);
        return orderDAO.list(param, new RowBounds(offset, limit));
    }

    @Override
    public int count(Long id, String code) {
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("code", code);
        return orderDAO.count(param);
    }

    /**
     * pps向pps-cloud同步订单数据
     *
     * @param orderList 要同步的数据
     * @return boolean
     */
    @Override
    public boolean upwardsSyncOrder(List<Order> orderList) {
        //1.验证数据合法性
        if (orderList == null || orderList.size() <= 0) {
            return false;
        }
        try {
            List<OrderDetail> orderDetailList;
            List<OrderTrace> orderTraceList;
            Map<String, Object> params;
            Order orderFlag;
            for (Order order : orderList) {
                //2.同步订单数据
                orderFlag = orderDAO.loadByCode(order.getCode());
                if (orderFlag == null) {
                    order.setSyncState(OrderSyncState.Synced.name());
                    orderDAO.insert(order);
                } else {
                    order.setSyncState(OrderSyncState.Synced.name());
                    orderDAO.update(order);
                }
                //记录同步追踪订单数据
                String desc = SyncTraceState.UpwardSyncOrder.val + ",数据模型[" + SyncTraceModel.Order.name() + "],数据编码-工厂编码[" + order.getCode() + "-" + order.getFactoryCode() + "]";
                String syncTraceCode = syncTraceSV.saveSyncTrace(order.getFactoryCode(), SyncTraceState.SyncSuccess.name(),
                        SyncTraceState.UpwardSync.name(), SyncTraceModel.Order.name(), order.getCode(), desc);
                //记录同步订单数据日志
                syncDataTraceSV.saveSyncDataTrace(syncTraceCode, order);

                orderDetailList = order.getOrderDetails();
                //3.同步订单详情
                if (orderDetailList != null && orderDetailList.size() > 0) {
                    //直接删除的原因是：如果绑定的箱体拆箱，拿出部分产品，pps系统中对应的订单详情会被删除，在pps-cloud系统中无法同步，所以此处直接全部删除，添加信息记录
                    params = new HashedMap();
                    params.put("orderCode", order.getCode());
                    orderDetailDAO.delete(params);
                    for (OrderDetail orderDetail : orderDetailList) {
                        orderDetail.setFactoryCode(order.getFactoryCode());
                        orderDetailDAO.insert(orderDetail);
                        //记录同步追踪订单详情数据
                        desc = SyncTraceState.UpwardSyncOrder.val + ",数据模型[" + SyncTraceModel.Order_Detail.name() + "],订单编码-工厂编码[" + order.getCode() + "-" + order.getFactoryCode() + "]";
                        syncTraceCode = syncTraceSV.saveSyncTrace(order.getFactoryCode(), SyncTraceState.SyncSuccess.name(),
                                SyncTraceState.UpwardSync.name(), SyncTraceModel.Order_Detail.name(), order.getCode(), desc);
                        //记录同步订单详情数据日志
                        syncDataTraceSV.saveSyncDataTrace(syncTraceCode, orderDetail);

                    }
                }
                //4.同步订单跟踪
                orderTraceList = order.getOrderTraces();
                if (orderTraceList != null && orderTraceList.size() > 0) {
                    params = new HashedMap();
                    params.put("itemOrderCode", order.getCode());
                    //直接删除的原因是：无法判断本次同步哪些状态是更新，哪些是新增。所以此处直接删除，添加新的记录信息
                    orderTraceDAO.delete(params);
                    orderTraceDAO.batchInsert(orderTraceList);
                }
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

}
